package cn.starrysky108.simpleerp.system.controller;


import cn.starrysky108.simpleerp.core.base.BaseResponseEntity;
import cn.starrysky108.simpleerp.core.enums.ResultCodeEnum;
import cn.starrysky108.simpleerp.core.exception.StorageException;
import cn.starrysky108.simpleerp.core.util.UploadUtil;
import cn.starrysky108.simpleerp.system.response.UploadResponse;
import cn.starrysky108.simpleerp.system.service.SystemFileService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源文件表 前端控制器
 * </p>
 *
 * @author Carl Lee
 * @since 2021-08-14
 */
@RestController
@RequestMapping("/system/files")
public class SystemFileController {
    private final SystemFileService service;

    @Autowired
    public SystemFileController(SystemFileService service) {
        this.service = service;
    }

    /**
     * 多文件上传
     *
     * @return 返回成功上传的文件信息
     */
    @PostMapping
    @ApiOperation("多文件上传")
    public BaseResponseEntity<List<UploadResponse>> upload(MultipartFile[] files) {
        Assert.notNull(files, "参数不能为空");
        ArrayList<UploadResponse> result = new ArrayList<>();
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                result.add(service.store(file));
            }
        }
        return BaseResponseEntity.success(result);
    }

    @GetMapping
    public List<String> getAllFiles() {
        return service.loadAll().map(
                        path -> MvcUriComponentsBuilder.fromMethodName(this.getClass(),
                                "getFileByPath", path.getFileName().toString()).build().toUri().toString())
                .collect(Collectors.toList());
    }

    @GetMapping("/{fileId:.+}")
    @ApiOperation("根据文件id下载文件")
    public ResponseEntity<Resource> getFileById(@PathVariable Long fileId) {
        Resource file = service.loadById(fileId);
        if (ObjectUtils.isEmpty(fileId) || ObjectUtils.isEmpty(file)) {
            throw new StorageException(ResultCodeEnum.FILE_LOAD_FAILED, String.valueOf(fileId));
        }
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + UploadUtil.getFileName(file.getFilename()) + "\"").body(file);
    }

    /**
     * 尚未完成文件权限检查，目前所有人都可以删除
     */
    @DeleteMapping("/{fileId:.+}")
    @ApiOperation("删除文件")
    public Boolean delete(@PathVariable Long fileId) {
        return service.delete(fileId);
    }
}